package com.hzmall.service.impl;

import ch.qos.logback.core.status.StatusListenerAsList;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzmall.common.ResponseCode;
import com.hzmall.common.ServerResponse;
import com.hzmall.dao.CategoryMapper;
import com.hzmall.dao.ProductMapper;
import com.hzmall.pojo.Category;
import com.hzmall.pojo.Product;
import com.hzmall.service.IProductService;
import com.hzmall.util.DateTimeUtil;
import com.hzmall.util.FileUploadUtil;
import com.hzmall.util.FtpUtil;
import com.hzmall.util.PropertiesUtil;
import com.hzmall.vo.ProductDetailVo;
import com.hzmall.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

@Service("productService")
@Slf4j
public class ProductService implements IProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    //产品搜索及动态排序
    public ServerResponse list(Integer categoryId, String keywords, Integer pageNum, Integer pageSize, String orderBy){
        if (StringUtils.isBlank(keywords) && categoryId == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUEMENT.getCode(),ResponseCode.ILLEGAL_ARGUEMENT.getDesc());
        }
        Set<String> orderBySet = new HashSet<String>();
        orderBySet.add("price_desc");
        orderBySet.add("price_asc");
        PageHelper.startPage(pageNum, pageSize);
        if (StringUtils.isNotBlank(orderBy)){
            if (orderBySet.contains(orderBy)){
                String[] orderByKeys = orderBy.split("_");
                PageHelper.orderBy(orderByKeys[0]+" "+orderByKeys[1]);
            }
        }
        keywords = new StringBuilder().append("%").append(keywords).append("%").toString();
        List<Product> productList = this.productMapper.selectProductByCategoryIdAndProductName(categoryId, keywords);
        List<ProductVo> productVoList = convertPOJO2VO(productList);
        PageInfo pageInfo = new PageInfo(productList);
        pageInfo.setList(productVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    //POJO转VO
    private List<ProductVo> convertPOJO2VO(List<Product> productList){
        List<ProductVo> productVoList = new ArrayList<ProductVo>();
        for (Product productItem : productList){
            ProductVo productVo = new ProductVo();
            productVo.setId(productItem.getId());
            productVo.setCategoryId(productItem.getCategoryId());
            productVo.setName(productItem.getName());
            productVo.setMainImage(productItem.getMainImage());
            productVo.setPrice(productItem.getPrice());
            productVo.setSubtitle(productItem.getSubtitle());
            productVo.setImageHost(PropertiesUtil.getStringProperty("ftp.server.http.prefix"));
            productVoList.add(productVo);
        }
        return productVoList;
    }

    //商品详情
    public ServerResponse detail(Integer productId){
        if (productId == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUEMENT.getCode(),ResponseCode.ILLEGAL_ARGUEMENT.getDesc());
        }
        Product product = this.productMapper.selectByPrimaryKey(productId);
        if (product == null){
            return ServerResponse.createByErrorMessage("该商品不存在");
        }
        if (product.getStatus() != 1){
            return ServerResponse.createByErrorMessage("该商品已下架或删除");
        }
        return ServerResponse.createBySuccess(product);
    }


                //后台逻辑
    //----------------------------------------------------------------------
    //后台商品列表
    public ServerResponse backendList(Integer pageNum,Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Product> productList = this.productMapper.selectAllProducts();
        List<ProductVo> productVoList = convertPOJO2VO(productList);
        PageInfo pageInfo = new PageInfo(productList);
        pageInfo.setList(productVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    //商品搜索
    public ServerResponse backendSearch(String productName,Integer productId,Integer pageNum,Integer pageSize){
        if (StringUtils.isBlank(productName) && productId == null){
            return ServerResponse.createByErrorMessage("参数错误,productName和productId必须传入一个");
        }
        PageHelper.startPage(pageNum,pageSize);
        productName = new StringBuilder().append("%").append(productName).append("%").toString();
        List<Product> productList = this.productMapper.selectProductByProductNameAndProductId(productName, productId);
        List<ProductVo> productVoList = new ArrayList<ProductVo>();
        productVoList = convertPOJO2VO(productList);
        PageInfo pageInfo = new PageInfo(productList);
        pageInfo.setList(productVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    //图片上传
    public ServerResponse upload(MultipartFile upload_file, HttpServletRequest request){
        if (upload_file.getSize() == 0 || upload_file.isEmpty()){
            return ServerResponse.createByErrorMessage("文件不存在");
        }
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = FileUploadUtil.upload(upload_file,path);
        Map<String,String> map = new HashMap();
        if (fileName != null){
            map.put("uri",fileName);
            map.put("url",PropertiesUtil.getStringProperty("ftp.server.http.prefix")+fileName);
            return ServerResponse.createBySuccess(map);
        }
        return ServerResponse.createByErrorMessage("上传失败");
    }

    //商品详情
    public ServerResponse backendDetail(Integer productId){
        Product product = this.productMapper.selectByPrimaryKey(productId);
        if (product == null){
            return ServerResponse.createByErrorMessage("找不到该商品");
        }
        ProductDetailVo productDetailVo = convertProduct2ProductDetailVo(product);
        return ServerResponse.createBySuccess(productDetailVo);
    }

    private ProductDetailVo convertProduct2ProductDetailVo(Product product){
        ProductDetailVo productDetailVo = new ProductDetailVo();
        productDetailVo.setCategoryId(product.getCategoryId());
        productDetailVo.setCreateTime(DateTimeUtil.date2String(product.getCreateTime()));
        productDetailVo.setDetail(product.getDetail());
        productDetailVo.setId(product.getId());
        productDetailVo.setImageHost(PropertiesUtil.getStringProperty("ftp.server.http.prefix"));
        productDetailVo.setMainImage(product.getMainImage());
        productDetailVo.setName(product.getName());
        productDetailVo.setPrice(product.getPrice());
        productDetailVo.setStatus(product.getStatus());
        productDetailVo.setStock(product.getStock());
        productDetailVo.setSubImages(product.getSubImages());
        productDetailVo.setSubtitle(product.getSubtitle());
        productDetailVo.setUpdateTime(DateTimeUtil.date2String(product.getUpdateTime()));

        Category category = this.categoryMapper.selectByPrimaryKey(product.getCategoryId());
        if (category.getParentId() == 0){
            productDetailVo.setParentCategoryId(product.getCategoryId());
        }else{
            productDetailVo.setParentCategoryId(category.getParentId());
        }
        return productDetailVo;
    }

    //更改产品销售状态
    public ServerResponse setSaleStatus(Integer productId,Integer status){
        Product product = this.productMapper.selectByPrimaryKey(productId);
        Integer[] statusCode = {0,1};
        if (!Arrays.asList(statusCode).contains(status)){
            return ServerResponse.createByErrorMessage("状态码错误");
        }
        if (product == null){
            return ServerResponse.createByErrorMessage("该商品不存在");
        }
        if (product.getStatus().equals(status)){
            return ServerResponse.createBySuccessMessage("修改成功");
        }
        product.setStatus(status);
        Integer rows = this.productMapper.updateByPrimaryKeySelective(product);
        if (rows > 0){
            return ServerResponse.createBySuccessMessage("修改产品状态成功");
        }
        return ServerResponse.createByErrorMessage("修改产品状态失败");
    }

    //新增or更新产品
    public ServerResponse save(Product product){
        if (product == null){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        Category category = this.categoryMapper.selectByPrimaryKey(product.getCategoryId());
        if (category == null){
            return ServerResponse.createByErrorMessage("参数错误，品类不存在");
        }
        Integer[] status = {0,1};
        if (!Arrays.asList(status).contains(product.getStatus())){   //校验状态码
            return ServerResponse.createByErrorMessage("参数错误,status状态码错误");
        }
        if (product.getId() == null){  //id=null表示新增商品
            Integer rows = this.productMapper.insertSelective(product);
            if (rows > 0){
                return ServerResponse.createBySuccessMessage("新增商品成功");
            }else{
                return ServerResponse.createByErrorMessage("新增商品失败");
            }
        }else{  //id != null表示更新商品
            Product updateProduct = new Product();
            updateProduct.setId(product.getId());
            updateProduct.setCategoryId(product.getCategoryId());
            updateProduct.setName(product.getName());
            updateProduct.setSubtitle(product.getSubtitle());
            updateProduct.setMainImage(product.getMainImage());
            updateProduct.setSubImages(product.getSubImages());
            updateProduct.setDetail(product.getDetail());
            updateProduct.setPrice(product.getPrice());
            updateProduct.setStock(product.getStock());
            updateProduct.setStatus(product.getStatus());
            Integer rows = this.productMapper.updateByPrimaryKeySelective(updateProduct);
            if (rows > 0){
                return ServerResponse.createBySuccessMessage("更新商品成功");
            }else{
                return ServerResponse.createByErrorMessage("更新商品失败");
            }
        }
    }

    //富文本图片上传
    public Map backendRichTextImgUpload(MultipartFile upload_file,HttpServletRequest request){
        Map<String,String> resultMap = new HashMap<String, String>();
        if (upload_file.getSize() == 0 || upload_file.isEmpty()){
            resultMap.put("success","false");
            resultMap.put("msg","文件不存在");
            resultMap.put("file_path","null");
            return resultMap;
        }
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = FileUploadUtil.upload(upload_file,path);
        if (!StringUtils.isEmpty(fileName)){
            resultMap.put("file_path",PropertiesUtil.getStringProperty("ftp.server.http.prefix")+fileName);
            resultMap.put("msg","上传成功");
            resultMap.put("success","true");
            return resultMap;
        }
        resultMap.put("success","false");
        resultMap.put("msg","上传失败");
        resultMap.put("file_path","null");
        return resultMap;
    }
}
